<template>
  <div>
    <div v-if="Props.seatData != null">
      <div class="chart-wrapper" style="width: 360px">
        <el-button
          type="info"
          size="small"
          link
          @click="valueType = valueType == 'value' ? 'load' : 'value'"
        >
          <el-icon><Odometer /></el-icon>
          <span>数据切换:</span>
          <b>{{ valueType == "value" ? "架次" : "负荷" }}</b>
        </el-button>
        <div>
          <el-button
            type="info"
            link
            @click="refreshChart()"
            icon="Refresh"
          ></el-button>
          <el-button
            type="info"
            link
            @click="showRaw()"
            icon="Document"
          ></el-button>
          <el-button
            type="info"
            link
            @click="download()"
            icon="Download"
          ></el-button>
        </div>
      </div>
      <v-chart
        v-if="showChart"
        style="margin: 15px 0 5px 0"
        :option="option"
        ref="chart"
        :init-options="{ width: 360, height: 260 }"
      />
      <!-- autoresize -->
      <div class="legend-container">
        <span
          v-for="cell in gaugeData"
          :class="[
            'legend-tag',
            cell.value > 45 ? 'im' : '',
            summaryData.maxSeat == cell.name ? '' : '',
          ]"
          :style="{
            color: commonStore.darkMode ? '#1d1e1f' : '#ffffff',
            backgroundColor: cell.itemStyle.color,
          }"
        >
          <span>{{ cell.name }}</span>
          <!-- <span>:{{ cell.value }}</span> -->
        </span>
      </div>
    </div>
    <!-- <el-empty v-else /> -->
  </div>
</template>

<script setup>
// import echarts
import * as echarts from "echarts/core";
import { SVGRenderer, CanvasRenderer } from "echarts/renderers";

import { GaugeChart } from "echarts/charts";
import { TooltipComponent, LegendComponent } from "echarts/components";
import { LabelLayout } from "echarts/features";

// import vue echarts
import VChart, { THEME_KEY } from "vue-echarts";

// import vue apis
import { h, ref, computed, nextTick, watch, onMounted, onUnmounted } from "vue";
import { ElMessageBox, ElInput } from "element-plus";
import useCommonStore from "@/store/common.js";
import useFlowStore from "@/store/flow.js";

const commonStore = useCommonStore();
const flowStore = useFlowStore();

echarts.use([
  // SVGRenderer,
  CanvasRenderer,
  GaugeChart,
  TooltipComponent,
  LegendComponent,
  LabelLayout,
]);

const Props = defineProps({
  seatData: {
    type: Object,
    default: null,
  },
  dataStep: {
    type: Number,
    default: 4,
  },
});

const chart = ref();
const showChart = ref(true);

const refreshChart = async () => {
  showChart.value = false;
  await nextTick();
  showChart.value = true;
  await nextTick();
  if (chart == null || chart.value == null) {
    return null;
  } else {
    chart.value.resize();
  }
};

const showRaw = () => {
  ElMessageBox({
    title: "席位数据",
    message: h(
      "pre",
      {
        style: {
          fontFamily: "Consolas",
          fontSize: "12",
          height: "320px",
          overflow: "auto",
        },
      },
      [
        h("pre", null, JSON.stringify(summaryData.value, null, 2)),
        h(
          "div",
          {
            style: {
              width: "calc(100% - 30px)",
              margin: "24px 12px",
              borderBottom: "1px dotted rgba(128,128,128,0.5)",
            },
          },
          ""
        ),
        h("pre", null, JSON.stringify(Props.seatData, null, 2)),
      ]
    ),
  });
};

const download = () => {
  if (chart == null || chart.value == null) {
    return null;
  }
  let dataURL = chart.value.getDataURL();
  // console.log("dataURL", dataURL);
  const elink = document.createElement("a");
  elink.download = "seatData.svg"; // 设置默认文件名
  elink.style.display = "none";
  elink.href = dataURL;
  document.body.appendChild(elink);
  elink.click();
  URL.revokeObjectURL(elink.href); // 释放URL 对象
  document.body.removeChild(elink);
};

const valueType = ref("load");
const gaugeData = computed(() => {
  let data = [];
  for (let i = 0; i < Props.seatData.length; i++) {
    let cell = Props.seatData[i];
    let name = cell.seat;
    let value = valueType.value == "value" ? cell.value : cell.load;
    let color = commonStore.darkMode
      ? flowStore.seatColors[cell.seat][0]
      : flowStore.seatColors[cell.seat][1];
    data.push({ name, value, itemStyle: { color } });
  }
  return data;
});

const summaryData = computed(() => {
  let maxSeat = "";
  let maxValue = 0;
  let totalValue = 0;
  let seatCount = gaugeData.value.length;
  for (let i = 0; i < seatCount; i++) {
    let cell = gaugeData.value[i];
    totalValue += cell.value;
    if (cell.value > maxValue) {
      maxValue = cell.value;
      maxSeat = cell.name;
    }
  }
  let averageValue = Math.round(totalValue / seatCount);
  return { maxSeat, maxValue, averageValue };
});

const option = computed(() => {
  let axisThick = Math.min(Math.max(gaugeData.value.length * 10, 15), 45);
  // let maxValue = summaryData.value.maxValue;
  // let maxValue = Math.round((Props.dataStep * 0.8 + 4 * 0.2) * 16);
  let maxValue =
    valueType.value == "value"
      ? Math.round((Props.dataStep * 0.8 + 4 * 0.2) * 17)
      : Math.round((Props.dataStep * 0.85 + 4 * 0.15) * 13);

  return {
    tooltip: {
      show: true,
      trigger: "item",
    },
    // legend: { show: true, top: "bottom" },
    series: [
      {
        type: "gauge",
        startAngle: -120,
        endAngle: 300,
        radius: "100%",
        pointer: {
          show: false,
          // icon: "pin",
          // icon: "triangle",
          itemStyle: {
            // opacity: 0.5,
            borderWidth: 1,
            borderColor: commonStore.darkMode ? "#1d1e1f" : "#ffffff",
          },
        },
        progress: {
          show: true,
          overlap: false,
          roundCap: true,
          clip: false,
          itemStyle: {
            borderWidth: 1,
            borderColor: commonStore.darkMode ? "#1d1e1f" : "#ffffff",
            // opacity: 0.5,
          },
        },
        emphasis: { disabled: false },
        splitNumber: 5,
        title: { show: false },
        detail: { show: false },
        axisLine: {
          show: true,
          lineStyle: {
            width: axisThick,
            color: [
              [1, "rgba(128,128,128,0.1)"],
              // [0.4, "rgba(128,128,128,0.1)"],
              // [0.75, "rgba(103,194,58,0.15)"],
              // [0.9, "rgba(230,162,60,0.2)"],
              // [1, "rgba(245,108,108,0.25)"],
              //
              // [0.4, "rgba(128,128,128,0.1)"],
              // [0.75, "rgba(128,128,128,0.2)"],
              // [0.9, "rgba(128,128,128,0.35)"],
              // [1, "rgba(128,128,128,0.55)"],
              //
              // [0.3, "#67e0e3"],
              // [0.7, "#37a2da"],
              // [1, "#fd666d"],
            ],
          },
        },
        splitLine: { show: true, distance: 0, length: 10 },
        axisTick: { show: true },
        axisLabel: {
          show: true,
          distance: axisThick + 10,
          formatter: (value) => Math.round(value),
        },
        data: gaugeData.value,
        min: 0,
        max: maxValue,
      },
      {
        type: "gauge",
        startAngle: -120,
        endAngle: 300,
        radius: "100%",
        pointer: {
          show: true,
          icon: "pin",
          // 'circle', 'rect', 'roundRect', 'triangle', 'diamond', 'pin', 'arrow', 'none'
          length: 25,
          offsetCenter: [0, -105],
          width: 15,
          itemStyle: {
            borderWidth: 1,
            borderColor: commonStore.darkMode ? "#1d1e1f" : "#ffffff",
            shadowColor: "#000",
            shadowBlur: 5,
          },
        },
        progress: { show: false },
        emphasis: { disabled: false },
        splitNumber: 5,
        title: { show: false },
        detail: { show: false },
        axisLine: { show: false },
        splitLine: { show: false },
        axisTick: { show: false },
        axisLabel: { show: false },
        // Primary: #409EFF
        // Success: #67C23A
        // Warning: #E6A23C
        // Danger: #F56C6C
        // Info: #909399
        data: [
          {
            value: Math.round(maxValue * 0.21),
            name: "酱油",
            itemStyle: {
              color: "#909399",
            },
          },
          {
            value: Math.round(maxValue * 0.4),
            name: "轻松",
            itemStyle: {
              color: "#409EFF",
              // color: "#67C23A",
            },
          },
          {
            value: Math.round(maxValue * 0.8),
            name: "关注",
            itemStyle: {
              color: "#E6A23C",
            },
          },
          {
            value: Math.round(maxValue * 0.99),
            name: "繁忙",
            itemStyle: {
              color: "#F56C6C",
            },
          },
        ],
        min: 0,
        max: maxValue,
      },
    ],
  };
});
</script>

<style scoped>
.chart-wrapper {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 3px 12px 0 12px;
}

.legend-container {
  width: 360px;
  min-height: 20px;
  margin: 0;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-wrap: wrap;
  overflow: none;
}

.legend-tag {
  font-weight: bold;
  font-size: 12px;
  font-family: Consolas;
  margin: 0 2px;
  padding: 1px 3px;
  border-radius: 4px;
  opacity: 0.5;
  cursor: pointer;
  transition: all 0.3s ease-in-out;
}

.legend-tag:hover {
  opacity: 1;
}

@keyframes im_icon {
  0% {
    /* opacity: 0.5; */
    /* transform: translate(0, 0); */
    transform: rotate(0deg);
  }
  25% {
    /* opacity: 1; */
    /* transform: translate(0, -1px); */
    transform: rotate(3deg);
  }
  75% {
    /* opacity: 1; */
    /* transform: translate(0, 1px); */
    transform: rotate(-3deg);
  }
  100% {
    /* opacity: 0.5; */
    /* transform: translate(0, 0); */
    transform: rotate(0deg);
  }
}
.im {
  opacity: 1;
  /* transform: scale(1.2); */
  animation: im_icon 0.2s infinite;
  /* font-size:13px; */
}
</style>
